package com.yonyou.crm.cum.customer.service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.yonyou.crm.common.biz.service.BaseBizServiceImpl;
import com.yonyou.crm.cum.customer.entity.CustomerViewDO;
import com.yonyou.iuap.context.InvocationInfoProxy;

@Service
public class CustomerViewBizServiceImpl extends BaseBizServiceImpl<CustomerViewDO> {
	
	private int isExist(Long cumId) {
		String userIdStr = (String)InvocationInfoProxy.getParameter("id");//用户id
		String orgIdStr = (String)InvocationInfoProxy.getParameter("orgid");//所属公司
		String tenantIdStr = (String)InvocationInfoProxy.getTenantid();
		Long userId = Long.parseLong(userIdStr);
		Long orgId = Long.parseLong(orgIdStr);
		Long tenantId = Long.parseLong(tenantIdStr);
		
		Map<String, Object> param = new HashedMap<String, Object>();
		param.put("cumId", cumId);
		param.put("userId", userId);
		param.put("tenantId", tenantId);
		param.put("orgId", orgId);
		
		int count = dao.countAll(CustomerViewDO.class, "isExist", param);
		if (count > 0) {
			return 1;
		}
		return 0;
	}
	
	@Override
	public void beforeSaveVO(CustomerViewDO vdo) {
		super.beforeSaveVO(vdo);

		int isExist = isExist(vdo.getCumId());
		if (isExist >= 1) {
			delete(vdo);
		}
		String userIdStr = (String)InvocationInfoProxy.getParameter("id");//用户id
		String deptIdStr = (String)InvocationInfoProxy.getParameter("deptid");//所属部门
		String orgIdStr = (String)InvocationInfoProxy.getParameter("orgid");//所属公司
		Long userId = Long.parseLong(userIdStr);
		if (StringUtils.isEmpty(deptIdStr)) {
			vdo.setDeptId(0L);
		} else {
			Long deptId = Long.parseLong(deptIdStr);
			vdo.setDeptId(deptId);
		}
		Long orgId = Long.parseLong(orgIdStr);
		Date date = new Date();
		
		vdo.setOrgId(orgId);
		vdo.setUserId(userId);
		vdo.setCreatedTime(date);
	}
	
	public int delete(CustomerViewDO vdo) {
		String userIdStr = (String)InvocationInfoProxy.getParameter("id");//用户id
		String deptIdStr = (String)InvocationInfoProxy.getParameter("deptid");//所属部门
		String orgIdStr = (String)InvocationInfoProxy.getParameter("orgid");//所属公司
		String tenantIdStr = (String)InvocationInfoProxy.getTenantid();
		Long userId = Long.parseLong(userIdStr);
		if (StringUtils.isEmpty(deptIdStr)) {
			vdo.setDeptId(0L);
		} else {
			Long deptId = Long.parseLong(deptIdStr);
			vdo.setDeptId(deptId);
		}
		Long orgId = Long.parseLong(orgIdStr);
		Long tenantId = Long.parseLong(tenantIdStr);

		vdo.setUserId(userId);
		vdo.setOrgId(orgId);
		vdo.setTenantId(tenantId);
		
		return dao.deleteSql(CustomerViewDO.class, "delete", vdo);
	}
	
	public int batchDeleteByCumIds(String[] cumIds) {
		Map<String, Object> paraMap = new HashMap<String, Object>();
		paraMap.put("cumIds", cumIds);
		
		return dao.deleteSql(CustomerViewDO.class, "batchDeleteByCumIds", paraMap);
	}
	
}
